<template>
  <div>
    <Dialog v-model="dialogVisible" :title="dialogTitle" @closed="close" width="830px">
      <el-form
        ref="formRef"
        :model="formData"
        :formRules="formRules"
        label-width="160px"
        v-loading="formLoading"
      >
        <el-form-item  label="渠道费率" prop="feeRate">
          <el-input v-model="formData.feeRate" placeholder="请输入渠道费率" clearable>
            <template #append>%</template>
          </el-input>
        </el-form-item>

        <el-form-item  label="开放平台 APPID" prop="config.appId">
          <el-input v-model="formData.config.appId" placeholder="请输入开放平台 APPID" clearable />
        </el-form-item>

         <el-form-item  label="密钥" prop="config.privateKey">
          <el-input v-model="formData.config.privateKey" />
        </el-form-item>
        <el-form-item  label="应用公钥版本号" prop="config.keyVersion">
          <el-input v-model="formData.config.keyVersion"/>
        </el-form-item> 
        <el-form-item  label="渠道状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in getDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="parseInt(dict.value)"
              :label="parseInt(dict.value)"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>     

       

        <el-form-item  label="签名方式" prop="config.signType">
          <el-input v-model="formData.config.signType"/>
        </el-form-item>

        <el-form-item  label="支付令牌" prop="config.payToken">
          <el-input v-model="formData.config.payToken"/>
        </el-form-item>

        <el-form-item  label="盐值" prop="config.salt">
          <el-input v-model="formData.config.salt"/>
        </el-form-item>

        <el-form-item  label="支付接口" prop="config.payApiUrl">
          <el-input v-model="formData.config.payApiUrl"/>
        </el-form-item>

        <el-form-item label="支付回调通知接口" prop="config.notifyUrl">
          <el-input v-model="formData.config.notifyUrl"/>
        </el-form-item>

         <el-form-item label="支付查询接口" prop="config.queryOrderUrl">
          <el-input v-model="formData.config.queryOrderUrl"/>
        </el-form-item>

        <el-form-item label="退款请求接口" prop="config.refundApiUrl">
          <el-input v-model="formData.config.refundApiUrl"/>
        </el-form-item>

        <el-form-item label="退款回调接口" prop="config.refundNotifyUrl">
          <el-input v-model="formData.config.refundNotifyUrl"/>       
        </el-form-item>
        
        <el-form-item label="退款查询接口" prop="config.queryRefundOrderUrl">
          <el-input v-model="formData.config.queryRefundOrderUrl" />
        </el-form-item> 

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" :style="{ width: '100%' }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { CommonStatusEnum } from '@/utils/constants'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import * as ChannelApi from '@/api/pay/channel'

defineOptions({ name: 'AlipayChannelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<any>({
  appId: '',
  code: '',
  status: undefined,
  feeRate: undefined,
  remark: '',
  config: {
    appId: '',
    payApiUrl: null,
    notifyUrl: '',
    refundNotifyUrl: '',
    salt: '',
    payToken: '',
    queryOrderUrl: '',
    refundApiUrl: '',
    queryRefundOrderUrl: '',
    signType: '',
    keyVersion: null,
    privateKey: ''
  }
})
const formRules = {
  feeRate: [{ required: true, message: '请输入渠道费率', trigger: 'blur' }],
  status: [{ required: true, message: '渠道状态不能为空', trigger: 'blur' }],
  'config.appId': [{ required: true, message: '请输入开放平台上创建的应用的 ID', trigger: 'blur' }],
  'config.payApiUrl': [{ required: true, message: '请传入支付接口', trigger: 'blur' }],
  'config.notifyUrl': [{ required: true, message: '请传入支付回调通知接口', trigger: 'blur' }],
  'config.salt': [{ required: true, message: '请传入支付盐值', trigger: 'blur' }],
  'config.payToken': [{ required: true, message: '请传入支付回调通知接令牌', trigger: 'blur' }],
  'config.refundNotifyUrl': [{ required: true, message: '请传入退款回调通知接口', trigger: 'blur' }],
  'config.refundApiUrl': [{ required: true, message: '请传入退款接口', trigger: 'blur' }],
  'config.queryRefundOrderUrl': [{ required: true, message: '请传入退款查询接口', trigger: 'blur' }],
  'config.queryOrderUrl': [{ required: true, message: '请传入支付查询接口', trigger: 'blur' }],
  'config.signType': [{ required: true, message: '请传入签名算法类型', trigger: 'blur' }],
  'config.keyVersion': [{ required: true, message: '请输入密钥版本号', trigger: 'blur' }],
  'config.privateKey': [{ required: true, message: '请输入商户私钥', trigger: 'blur' }],
}
const fileAccept = '.crt'
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (appId, code) => {
  dialogVisible.value = true
  formLoading.value = true
  resetForm(appId, code)
  // 加载数据
  try {
    const data = await ChannelApi.getChannel(appId, code)
    if (data && data.id) {
      formData.value = data
      formData.value.config = JSON.parse(data.config)
    }
    dialogTitle.value = !formData.value.id ? '创建支付渠道' : '编辑支付渠道'
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as ChannelApi.ChannelVO
    data.config = JSON.stringify(formData.value.config)
    if (!data.id) {
      await ChannelApi.createChannel(data)
      message.success(t('common.createSuccess'))
    } else {
      await ChannelApi.updateChannel(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = (appId, code) => {
  formData.value = {
    appId: appId,
    code: code,
    status: CommonStatusEnum.ENABLE,
    remark: '',
    feeRate: null,
    config: {
      appId: '',
      payApiUrl: null,
      notifyUrl: '',
      refundNotifyUrl: '',
      salt: '',
      payToken: '',
      queryOrderUrl: '',
      refundApiUrl: '',
      queryRefundOrderUrl: '',
      signType: '',
      keyVersion: null,
      privateKey: ''
    }
  }
  formRef.value?.resetFields()
}

</script>
